<template>
  <div class="box">
    <div class="item" style="width: 100%;line-height: 5rem;">
        <h2 style="text-align: center; font-weight: 500; font-size: 28px; margin-top: 20px; ">短信验证登录/注册</h2>
        <span style="text-align: center;">新手机注册，请详读使用协议、个人信息保护政策</span>
    </div>
    <van-form @submit="onSubmit">
      <van-cell-group inset>
        <van-field
          v-model="username"
          name="username"
          label="用户名"
          placeholder="用户名"
          :rules="[
            { pattern: pattern1, required: true, message: '请填写用户名' },
          ]"
        />
        <van-field
          v-model="password"
          type="password"
          name="password"
          label="密码"
          placeholder="密码"
          :rules="[
            { pattern: pattern2, required: true, message: '请填写密码' },
          ]"
        >
        </van-field>
      </van-cell-group>
      <van-field
        v-model="sms"
        label="获取验证码"
        placeholder="短信验证码"
        :rules="[{ required: true, message: '请点击获取短信验证码' }]"
      >
        <template #button>
          <van-button
            size="small"
            type="primary"
            v-if="time == 0"
            @click="getout"
          >
            获取验证码
          </van-button>
          <van-button size="small" type="primary" v-else disabled>
            {{ time }}s倒计时
          </van-button>
        </template>
      </van-field>
      <div style="margin: 16px">
        <van-button round block type="primary" native-type="submit">
          登录
        </van-button>
      </div>
    </van-form>
    <div style="width: 100%; text-align: right">
      <router-link to="/reg">立即注册?</router-link>
    </div>
  </div>
</template>

<script setup>
import { ref } from "vue";
import { loginApi } from "@/api/api";
import { showToast } from "vant";
import { useRoute, useRouter } from "vue-router";

const router = useRouter();
const route = useRoute();

const pattern1 = /^1[3-9]\d{9}$/;
const pattern2 = /^\d{6}$/;

const username = ref("");
const password = ref("");
const onSubmit = (values) => {
  console.log("submit", values);
  loginApi(username.value, password.value).then((res) => {
    if (res.data.code == 0) {
      showToast("登录成功");
      localStorage.setItem("token", res.data.data.token);
      localStorage.setItem("username", res.data.data.username);

      router.push("/");
    } else {
      showToast(res.data.msg);
    }
  });
};

const sms = ref("");
const time = ref(0);
const getout = () => {
  sms.value = Math.random().toString().slice(2, 8);
  time.value = 60;
  let timer = setInterval(() => {
    time.value--;
    if (time.value == 0) {
      clearInterval(timer);
    }
  }, 1000);
};
</script>

<style lang="scss" scoped></style>
